
from easysnmp import snmp_bulkwalk, snmp_get
from easysnmp.exceptions import EasySNMPError,EasySNMPConnectionError,EasySNMPTimeoutError


IP_OID = {
    "ip": "1.3.6.1.2.1.4.20.1.1",
    "mask": "1.3.6.1.2.1.4.20.1.3",
    "index": {
        "1.3.6.1.2.1.4.20.1.2": {
            "interface": "1.3.6.1.2.1.31.1.1.1.1",
            "description": "1.3.6.1.2.1.31.1.1.1.18"
        }
    },
}
COMMUNITY = "admin1234"
VERSION = 2

def scan_bulk_snmp(hostname: str, oids: str,) -> list:
    """遍历单个oid节点

    Args:
        hostname (str): 主机名或ip
        oids (str): 需要扫描的oid
    Returns:
        返回值: oid的值
    """
    res = snmp_bulkwalk(hostname=hostname, oids=oids, community=COMMUNITY, version=VERSION)
    return [i.value for i in res]


def scan_get_snmp( hostname: str, oid: str,)->str|int:
    """获取单个oid节点

    Args:
        hostname (str): 主机名或ip
        oid (str): 需要扫描的oid
    Returns:
        返回值: _description_
    """
    res = snmp_get(hostname=hostname, oids=oid, community=COMMUNITY, version=VERSION)
    return res.value


def scan_index_snmp(hostname: str, oids_dict=None)->dict|None:
    """_summary_
    根据传入的oids字典自动进行snmp扫描
    Args:
        hostname (str): 主机名或ip
        oids_dict (dict): 需要扫描的oid，字典类型
    """
    if oids_dict is None:
        oids_dict = IP_OID
    ip_port = {}
    try:
        for k, v in oids_dict.items():
            """
            将依赖索引的筛选出来单独执行，遍历出其它依赖这个索引的值
            """
            if k == "index":
                for index, value in v.items():
                    index_oid = scan_bulk_snmp(hostname=hostname, oids=index)
                    for sub_index, sub_value in value.items():
                        temp = [scan_get_snmp(hostname=hostname, oid=f"{sub_value}.{i}") for i in index_oid]
                        ip_port[sub_index] = temp
            else:
                """
                正常不依赖索引的oid直接遍历
                """
                ip_port[k] = scan_bulk_snmp(hostname=hostname, oids=v)
        return ip_port
    except EasySNMPTimeoutError as est:
        return None

